package link.anyauto.j2m.executor;

import android.os.Handler;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import link.anyauto.j2m.App;
import link.anyauto.j2m.ExecutorAct;

/**
 * Created by LYQ on 2016/5/12.
 */
public class ExecutorDemo {

    int max = 10;
    Handler uiHandler;

    public ExecutorDemo(Handler uiHandler) {
        this.uiHandler = uiHandler;
    }

    public void start() {

        new Thread(){
            @Override
            public void run() {
                try {
                    fixedThreadPool(3);
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    void fixedThreadPool(int size) throws Exception {
        final ExecutorService service = Executors.newFixedThreadPool(size);
        for (int i=0; i<max; i++) {
            final int last = i;
            final String name = "Task " + (i + 1);
            Future<Long> task = service.submit(new Callable<Long>() {
                @Override
                public Long call() throws Exception {
                    long res = timeConsumingJob(name);
                    if(last == 9) {
                        App.sleep(1000);
                        service.shutdown();
                    }
                    return res;
                }
            });
        }
    }

    long timeConsumingJob(String name) {
        long sleep = 500 + (long)(Math.random() * 500);
        App.sleep(sleep);
        uiHandler.obtainMessage(ExecutorAct.MSG_LOG, "任务【" + name + "】在线程【" + Thread.currentThread().getName() + "】中即将执行完毕，消耗时间：" + sleep + "毫秒。").sendToTarget();
        return sleep;
    }
}
